package com.example.a13001.shoppingmalltemplate;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.example.a13001.shoppingmalltemplate.View.SelfDialog;
import com.example.a13001.shoppingmalltemplate.View.SelfDialog1;
import com.example.a13001.shoppingmalltemplate.activitys.SettingActivity;
import com.example.a13001.shoppingmalltemplate.application.ShoppingMallTemplateApplication;
import com.example.a13001.shoppingmalltemplate.base.AppConstants;
import com.example.a13001.shoppingmalltemplate.base.BaseActivity;
import com.example.a13001.shoppingmalltemplate.event.AddShopCarEvent;
import com.example.a13001.shoppingmalltemplate.fragments.ClassifyFragment;
import com.example.a13001.shoppingmalltemplate.fragments.HomePageFragment;
import com.example.a13001.shoppingmalltemplate.fragments.MyFragment;
import com.example.a13001.shoppingmalltemplate.fragments.ShopCarFragment;
import com.example.a13001.shoppingmalltemplate.modle.AppConfig;
import com.example.a13001.shoppingmalltemplate.modle.CloaseAccount;
import com.example.a13001.shoppingmalltemplate.modle.CommonResult;
import com.example.a13001.shoppingmalltemplate.modle.LoginStatus;
import com.example.a13001.shoppingmalltemplate.modle.ShopCarGoods;
import com.example.a13001.shoppingmalltemplate.mvpview.ShopCarView;
import com.example.a13001.shoppingmalltemplate.presenter.ShopCarPredenter;
import com.example.a13001.shoppingmalltemplate.utils.CleanMessageUtil;
import com.example.a13001.shoppingmalltemplate.utils.ExampleUtil;
import com.example.a13001.shoppingmalltemplate.utils.HttpUtils;
import com.example.a13001.shoppingmalltemplate.utils.MyUtils;
import com.example.a13001.shoppingmalltemplate.utils.SPUtils;
import com.example.a13001.shoppingmalltemplate.utils.Utils;
import com.example.a13001.shoppingmalltemplate.utils.db.MyDateBaseHelpr;
import com.example.a13001.shoppingmalltemplate.utils.downloadTask;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jpush.android.api.JPushInterface;
import okhttp3.Call;
import util.UpdateAppUtils;

public class MainActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {
    @BindView(R.id.rb_main_my)
    RadioButton rbMainMy;
    private HomePageFragment mHomePageFragment;//首页
    private Fragment[] mFragments;
    private int mIndex = 0;
    private RadioGroup mRgMain;
    //    private DrawerLayout mDlMain;
    private NavigationView mNvLeft;
    private ListView mLvMainLeft;
    private RadioButton mRbClassify;
    private LinearLayout mLlLeft;
    private ClassifyFragment mClassifyFragment;
    private ShopCarFragment mShopCarFragment;
    private MyFragment myFragment;
    private RadioButton mRbHomepage;
    private static final String TAG = "MainActivity";
    private int NewAdId=0;//新的广告ID
    private String NewAdTitle="";//新的广告标题
    private String NewAdImags="";//新的广告图片
    private String NewAdLink="";//新的广告链接
    private String appPath="shopmall";
    private ShoppingMallTemplateApplication application;
    public static boolean isForeground = false;
    private RadioButton mRbShopCar;
    private ShopCarPredenter shopCarPredenter=new ShopCarPredenter(MainActivity.this);

    private String JsonUrl;
    private AppConfig mAppConfig;
    private SelfDialog1 selfDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        shopCarPredenter.onCreate();
        shopCarPredenter.attachView(shopCarView);
        shopCarPredenter.getAppConfig(AppConstants.COMPANY_ID);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        application= (ShoppingMallTemplateApplication) getApplicationContext();
        //获取远程JOSN网址
        JsonUrl=MyUtils.getMetaValue(MainActivity.this, "companyURL");
//        shopCarPredenter.onCreate();
//        shopCarPredenter.attachView(shopCarView);
//        shopCarPredenter.getAppConfig(AppConstants.COMPANY_ID);
        //获取APP初始配置文件
//        updateBarHandler.post(updateThread);
        String safetyCode = MyUtils.getMetaValue(this, "safetyCode");
        String code= Utils.md5(safetyCode+Utils.getTimeStamp());
        shopCarPredenter.getLoginStatus(AppConstants.COMPANY_ID,code,Utils.getTimeStamp(),AppConstants.FROM_MOBILE);
        intitView();
        initFragment();
        registerMessageReceiver();  // used for receive msg
//        setBasicSetup(1);
//        setBasicSetup(4);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getSter(String s) {
        Log.e(TAG, "getSter: " + s);
        if ("会员中心".equals(s)) {
            rbMainMy.setChecked(true);
        }
    }

    /**
     * 初始化控件
     */
    private void intitView() {
        mRgMain = findView(R.id.rg_main);
//        mDlMain = findView(R.id.dl_main);
        mLvMainLeft = findView(R.id.lv_main_left);
        mRbClassify = findView(R.id.rb_main_classify);
        mLlLeft = findView(R.id.ll_left);
        mRbHomepage = findView(R.id.rb_main_homepage);
        mRbShopCar = findView(R.id.rb_main_shopcar);

//        mRbClassify.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//
//                if (mDlMain.isDrawerOpen(mLlLeft)){
//                    mDlMain.closeDrawer(mLlLeft);
//                }else{
//                    mDlMain.openDrawer(mLlLeft);
//                }
//            }
//        });
//        List<String> list=new ArrayList<>();
//        list.add("辣妈推荐内衣");
//        list.add("美味手工点心");
//        list.add("百变洗护用品");
//        list.add("好身材养身包");
//        list.add("护眼养眼神器");
//        ArrayAdapter arrayAdapter=new ArrayAdapter(this,R.layout.item_classify,list);
//        mLvMainLeft.setAdapter(arrayAdapter);
        mRgMain.setOnCheckedChangeListener(this);

    }

    @Override
    public void setContentView(View view) {
        super.setContentView(view);

    }

    private void initFragment() {
        mHomePageFragment = HomePageFragment.newInstance("1");
        mClassifyFragment = ClassifyFragment.newInstance("1", "1");
        mShopCarFragment = ShopCarFragment.newInstance("shopcar", "1");
        myFragment = MyFragment.newInstance("a", "1");

        //添加到fragment数组
        mFragments = new Fragment[]{mHomePageFragment, mClassifyFragment, mHomePageFragment, mShopCarFragment, myFragment};
        //开启事务
        FragmentTransaction ft;
        ft = getSupportFragmentManager().beginTransaction();
        //添加首页
        ft.add(R.id.fl_main_content, mHomePageFragment).commit();
        //设置默认为第0个
        setIndexSelected(0);
        mRbHomepage.setChecked(true);

        if (getIntent() != null) {
            String mType=getIntent().getStringExtra("type");
            switch (mType){
                case "onLinepay":
                    setIndexSelected(4);
                    rbMainMy.setChecked(true);
                    break;
                case "Splash":
                    setIndexSelected(0);
                    mRbHomepage.setChecked(true);
                    break;
                case "Login":
                    setIndexSelected(0);
                    mRbHomepage.setChecked(true);
                    break;
                case "register":
                    setIndexSelected(0);
                    mRbHomepage.setChecked(true);
                    break;
                case "guid":
                    setIndexSelected(0);
                    mRbHomepage.setChecked(true);
                    break;
                case "shopcar":
                    setIndexSelected(3);
                    mRbShopCar.setChecked(true);
                    break;
                default:
                    setIndexSelected(0);
                    mRbHomepage.setChecked(true);
                    break;
            }
        }

    }


    public void setIndexSelected(int index) {

        if (mIndex == index) {
            return;
        }
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction ft = fragmentManager.beginTransaction();
        //隐藏当前fragment
        ft.hide(mFragments[mIndex]);
        if (!mFragments[index].isAdded()) {
            ft.add(R.id.fl_main_content, mFragments[index]).show(mFragments[index]);
        } else {
            ft.show(mFragments[index]);
        }
        ft.commit();
        //再次赋值
        mIndex = index;
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i) {
        switch (i) {
            //首页
            case R.id.rb_main_homepage:
                setIndexSelected(0);
                break;
            //分类
            case R.id.rb_main_classify:
                setIndexSelected(1);

                break;
            //消息
            case R.id.rb_main_message:
                setIndexSelected(2);
                break;
            //购物车
            case R.id.rb_main_shopcar:
                Log.e("ddd", "onCheckedChanged: "+"" );
                EventBus.getDefault().post(new AddShopCarEvent("成功"));
                setIndexSelected(3);
                break;
            //我的
            case R.id.rb_main_my:
                setIndexSelected(4);
                break;
        }
    }
    //通过线程下载远程广告图片
    public void DownLoadAdImages(){
        //指定下载路径为系统下载文件夹
        String path = Environment.getExternalStorageDirectory()
                + "/" + appPath + "/";
        File file = new File(path);
        // 如果SD卡目录不存在创建
        if (!file.exists()) {
            file.mkdir();
        }
        //删除旧的广告图片
        File filename = new File(path + Utils.md5(String.valueOf(application.getAdId())));
        if (filename.exists()){
            filename.delete();
        }
        //开始文件下载
        String filepath = path + Utils.md5(String.valueOf(NewAdId)) + ".jpg";
        //开始下载广告图片文件
        downloadTask task = new downloadTask(NewAdImags, 5, filepath, null, null);
        task.start();
    }
    //线程返回APP配置文件执行结果
    Handler updateBarHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.arg1==0){
//                Utils.MsgBox(getResources().getString(R.string.tips),msg.obj.toString(),MainActivity.this);
            } else {

                //判断是否需要下载广告
                if (NewAdId>0){
                    DownLoadAdImages();
                }
                //记录新的配置信息
                MyDateBaseHelpr db=new MyDateBaseHelpr(MainActivity.this);
                if (application.getStatus()==0){
                    ContentValues cv=new ContentValues();
                    cv.put("status", 1);
                    if (NewAdId>0){
                        //记录新的广告信息
                        cv.put("adSatus", 1);
                        cv.put("adid", NewAdId);
                        cv.put("adTitle", NewAdTitle);
                        cv.put("adImages", Utils.md5(String.valueOf(NewAdId)) + ".jpg");
                        cv.put("adLink", NewAdLink);
                    } else {
                        cv.put("adSatus", 0);
                    }
                    db.insert("zfy_config",cv);
                    application.setStatus(1);
                } else {
                    ContentValues cv=new ContentValues();
                    if (NewAdId>0){
                        cv.put("adSatus", 1);
                        cv.put("adid", NewAdId);
                        cv.put("adTitle", NewAdTitle);
                        cv.put("adImages", Utils.md5(String.valueOf(NewAdId)) + ".jpg");
                        cv.put("adLink", NewAdLink);
                        db.update("zfy_config",cv, null, null);
                    } else if (NewAdId==-1){
                        cv.put("adSatus", 0);
                        db.update("ad_config",cv, null, null);
                    }
                }
                db.close();
            }
//            updateBarHandler.removeCallbacks(updateThread);
        }
    };
    //通过线程从远程服务器读取配置文件
//    Runnable updateThread = new Runnable() {
//        public void run() {
//            Message msg = updateBarHandler.obtainMessage();
//            //获取APP配置JSON数据并返回
//            HttpUtils.ReMessage GetJsonData=new HttpUtils.ReMessage();
//            //Log.d("MainActivity","JSON URL:" + JsonUrl + "config/api.ashx?cdkey=" + IfySiteKey + "&timestamp=" + IfyTimeStamp + "");
//            GetJsonData=HttpUtils.getJsonContent(JsonUrl + "/api/json/app/app.ashx?action=config" + "&companyid=" + AppConstants.COMPANY_ID);
//            //打印日志
//            Log.d("MainActivity","JSON:" + GetJsonData.getContent());
//            //拆解JSON数据
//            try {
//                JSONObject jsonObject = new JSONObject(GetJsonData.getContent());
//                if (jsonObject.getInt("status")==0) {
//                    //配置信息校验失败
//                    msg.arg1=0;
//                    if (jsonObject.getString("errcode").equals("10000")){
//                        //安全校验失败
//                        msg.obj=getResources().getString(R.string.error003);
//                    } else if (jsonObject.getString("errcode").equals("10001") || jsonObject.getString("errcode").equals("10002")){
//                        //JSON获取失败
//                        msg.obj=getResources().getString(R.string.error003);
//                    }
//                } else {
//                    //配置信息校验成功，并正确解析JSON数据
//                    msg.arg1 = GetJsonData.getStatus();
//                    //判断是否开启了广告
//                    if (jsonObject.getInt("adSatus")==1){
//                        if (jsonObject.getInt("photoId")!=application.getAdId()){
//                            NewAdId=jsonObject.getInt("photoId");//记录要更新的广告ID
//                            NewAdTitle=jsonObject.getString("adTtile");//记录更新的广告标题
//                            NewAdImags=jsonObject.getString("adImages");//记录要更新的广告图片
//                            NewAdLink=jsonObject.getString("adLink");//记录要更新广告链接
//                        }
//                    } else {
//                        NewAdId=-1;
//                    }
//                }
//            }catch (Exception e) {
//                msg.arg1=0;
//                msg.obj=getResources().getString(R.string.error004);
//            }
//            updateBarHandler.sendMessage(msg);
//        }
//    };
    @Override
    protected void onResume() {
        isForeground = true;
        super.onResume();
    }


    @Override
    protected void onPause() {
        isForeground = false;
        super.onPause();
    }
    //for receive customer msg from jpush server
    private MessageReceiver mMessageReceiver;
    public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";

    public void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, filter);
    }

    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                    String messge = intent.getStringExtra(KEY_MESSAGE);
                    String extras = intent.getStringExtra(KEY_EXTRAS);
                    StringBuilder showMsg = new StringBuilder();
                    showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
                    if (!ExampleUtil.isEmpty(extras)) {
                        showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
                    }
                    setCostomMsg(showMsg.toString());
                }
            } catch (Exception e){
            }
        }
    }

    private void setCostomMsg(String msg){
        Toast.makeText(application, ""+msg, Toast.LENGTH_SHORT).show();
//        if (null != msgText) {
//            msgText.setText(msg);
//            msgText.setVisibility(android.view.View.VISIBLE);
//        }
    }
    /**
     * 1-2-3-4
     * 增、删、改、查
     */
    public void setBasicSetup(int type) {
        if (type == 1) {
            //设置别名（新的调用会覆盖之前的设置）
            JPushInterface.setAlias(this, 0, "0x123");
            //设置标签（同上）
            JPushInterface.setTags(this, 0, setUserTags());
        } else if (type == 2) {
            //删除别名
            JPushInterface.deleteAlias(this, 0);
            //删除指定标签
            JPushInterface.deleteTags(this, 0, setUserTags());
            //删除所有标签
            JPushInterface.cleanTags(this, 0);
        } else if (type == 3) {
            //增加tag用户量(一般都是登录成功设置userid为目标，在别处新增加比较少见)
            JPushInterface.addTags(this, 0, setUserTags());
        } else if (type == 4) {
            //查询所有标签
            JPushInterface.getAllTags(this, 0);
            //查询别名
            JPushInterface.getAlias(this, 0);
            //查询指定tag与当前用户绑定的状态（MyJPushMessageReceiver获取）
            JPushInterface.checkTagBindState(this, 0, "0x123");
            //获取注册id

            JPushInterface.getRegistrationID(this);
        }
    }
    /**
     * 标签用户
     */
    private static Set<String> setUserTags() {
        //添加3个标签用户（获取登录userid较为常见）
        Set<String> tags = new HashSet<>();
        tags.add("outsider");
        return tags;
    }
    /**
     * 标签用户
     */
    private static Set<String> setUserTags1() {
        //添加3个标签用户（获取登录userid较为常见）
        Set<String> tags = new HashSet<>();
        tags.add("member");
        return tags;
    }
    ShopCarView shopCarView=new ShopCarView() {
        @Override
        public void onSuccess(ShopCarGoods shopCarGoods) {
            Log.e(TAG, "onSuccess: "+shopCarGoods.toString() );
            int status = shopCarGoods.getStatus();
            if (status>0){
//                badge1.setText(String.valueOf(shopCarGoods.getSum()));
            }else{

            }
        }
        //获取配置信息
        @Override
        public void onSuccessGetAppConfig(AppConfig appConfig) {
            Log.e(TAG, "onSuccessGetAppConfig: "+appConfig.toString() );
            mAppConfig=appConfig;
            int status=appConfig.getStatus();
            if (status>0){
                int appStatus = appConfig.getAppStatus();//APP状态，1 启用全部 2 仅启用苹果版 3 仅用启安卓版 0 锁定
                if (appStatus==0||appStatus==2){
                    selfDialog = new SelfDialog1(MainActivity.this);
                    selfDialog.setTitle("您的APP服务已终止，请联系管理员");
                    selfDialog.setCancelable(false);
                    selfDialog.setYesOnclickListener("确定", new SelfDialog1.onYesOnclickListener() {
                        @Override
                        public void onYesClick() {
                            selfDialog.dismiss();
                            android.os.Process.killProcess(android.os.Process.myPid());
                        }
                    });

                    selfDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            backgroundAlpha(1f);
                        }
                    });
                    backgroundAlpha(0.6f);
                    selfDialog.show();
                    return;
                }
                String appVersion = appConfig.getAppVersion();
                String appAndroidApk = appConfig.getAppAndroidApk();
                UpdateAppUtils.from(MainActivity.this)
                        .checkBy(UpdateAppUtils.CHECK_BY_VERSION_CODE) //更新检测方式，默认为VersionCode
                        .serverVersionCode(Integer.parseInt(appVersion))
                        .apkPath(AppConstants.INTERNET_HEAD+appAndroidApk)
                        .showNotification(true) //是否显示下载进度到通知栏，默认为true
//                        .updateInfo(info)  //更新日志信息 String
                        .downloadBy(UpdateAppUtils.DOWNLOAD_BY_APP) //下载方式：app下载、手机浏览器下载。默认app下载
                        .isForce(false) //是否强制更新，默认false 强制更新情况下用户不同意更新则不能使用app
                        .update();
                int photoId = (int) SPUtils.get(AppConstants.photoId,0);
                if (photoId!=0){
                    if (photoId!=appConfig.getAppAd().getPhotoId()){
                        downAppAd(appConfig.getAppAd().getPhotoPath());
                    }else{

                    }
                }else{
                    downAppAd(appConfig.getAppAd().getPhotoPath());
                }
            }else{
                selfDialog = new SelfDialog1(MainActivity.this);
                selfDialog.setTitle("您的APP服务已终止，请联系管理员");
                selfDialog.setYesOnclickListener("确定", new SelfDialog1.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        selfDialog.dismiss();
                        android.os.Process.killProcess(android.os.Process.myPid());
                    }
                });
                selfDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        backgroundAlpha(1f);
                    }
                });
                backgroundAlpha(0.6f);
                selfDialog.show();
                Message msg = updateBarHandler.obtainMessage();
                msg.arg1=0;
                    //安全校验失败
                msg.obj=appConfig.getReturnMsg();

            }
        }

        @Override
        public void onSuccessLoginStatus(LoginStatus loginStatus) {
            Log.e(TAG, "onSuccessLoginStatus: "+loginStatus.toString() );
            if (loginStatus.getStatus()>0){
                //设置标签（同上）
                JPushInterface.setTags(MainActivity.this, 0, setUserTags1());
            }else{
                JPushInterface.setTags(MainActivity.this, 0, setUserTags());

            }
        }


        @Override
        public void onSuccessDeleteShopCar(CommonResult commonResult) {

        }

        @Override
        public void onSuccessDoCloaseAccount(CloaseAccount cloaseAccount) {

        }

        @Override
        public void onSuccessUpdateShopCarNum(CommonResult commonResult) {

        }

        @Override
        public void onError(String result) {

        }
    };
    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }
    private void downAppAd(String photoPath) {
        String path = Environment.getExternalStorageDirectory() + "/" + appPath + "/";
        OkHttpUtils.get()
                .url(AppConstants.INTERNET_HEAD+photoPath)
                .build()
                .execute(new FileCallBack(path,mAppConfig.getAppAd().getPhotoId()+".jpg") {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e(TAG, "onError: "+e.toString() );
                    }

                    @Override
                    public void onResponse(File response, int id) {
                        Log.e(TAG, "onResponse: "+response.getAbsolutePath());
                        if (!TextUtils.isEmpty(response.getAbsolutePath())){
                            SPUtils.put(AppConstants.photoId,mAppConfig.getAppAd().getPhotoId());
                            SPUtils.put(AppConstants.photoName,mAppConfig.getAppAd().getPhotoName());
                            SPUtils.put(AppConstants.photoPath,mAppConfig.getAppAd().getPhotoPath());
                            SPUtils.put(AppConstants.photoLink,mAppConfig.getAppAd().getPhotoLink());
                        }else{

                        }
                    }
                });
    }
}
